package com.caishi.lkx.gateway.context;

import com.zzw.common.resolver.KerayHandlerMethodArgumentResolver;
import com.zzw.common.resolver.KerayHandlerMethodArgumentResolverConfig;
import com.caishi.lkx.common.context.TokenData;
import com.caishi.lkx.common.context.UserContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.util.Map;

/**
 * token参数解析
 */
@Configuration
public class TokenParamResolver implements KerayHandlerMethodArgumentResolver {

    @Resource
    private UserContext userContext;


    public TokenParamResolver(KerayHandlerMethodArgumentResolverConfig kerayHandlerMethodArgumentResolverConfig) {
        kerayHandlerMethodArgumentResolverConfig.addKerayResolver(this);
    }

    private boolean userId(MethodParameter parameter) {
        return parameter.getParameterType() == Long.class && "userId".equals(parameter.getParameterName());
    }


    @Override
    public boolean supportsParameter(MethodParameter parameter, NativeWebRequest webRequest, Map<Object, Object> threadLocal) {
        return userId(parameter) ||
                parameter.getParameterType() == TokenData.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory, Map<Object, Object> threadLocal) throws Exception {
        var tokenData = userContext.currentTokenData();
        if (parameter.getParameterType() == TokenData.class) return tokenData;
        return tokenData.getUserId();
    }

    @Override
    public int getOrder() {
        return 10;
    }

}
